package hn.cch.spring.boot.controller;

import hn.cch.spring.boot.message.request.UploadRequest;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RequestMapping(value = "/io")
@RestController
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    /**
     * 上传多个文件
     * 两种方式都是使用form-data形式提交post方法http请求
     */

    @PostMapping(value = "uploadMore")
    public ResponseEntity<String> uploadMore(@RequestParam("file0") MultipartFile file0,
                                             @RequestParam("file1") MultipartFile file1) {

        try {
            List<MultipartFile> files = new ArrayList<>();
            files.add(file0);
            files.add(file1);

            for (MultipartFile file : files) {
                logger.info("file:{}", readFile(file));
            }
        } catch (Exception e) {
            logger.error("download Exception:", e);
        }

        return ResponseEntity.status(HttpStatus.OK).build();
    }

    @PostMapping(value = "uploadFile")
    public String uploadFile(HttpServletRequest request) {

        // 这里需求类型转换
        if (request instanceof MultipartHttpServletRequest) {
            Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
            logger.info("{}", fileMap.size());

            for (MultipartFile file : fileMap.values()) {
                logger.info("file:{}", readFile(file));
            }
        }
        return "OK";
    }


    @PostMapping(value = "uploadForm")
    public String uploadForm(UploadRequest uploadRequest, @RequestParam("file") MultipartFile file) {

        logger.info("UploadRequest:{}", uploadRequest.toString());
        logger.info("file:{}", readFile(file));

        String[] temp = {uploadRequest.getPath(), uploadRequest.getName()};
        String path = String.join(File.separator, temp);
        logger.info("writeLocal:{}", writeLocal(file, path));

        return "OK";
    }


    /**
     * 上传文件写入本地
     *
     * @param file
     * @param path
     * @return
     */
    public Boolean writeLocal(MultipartFile file, String path) {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            inputStream = file.getInputStream();
            byte[] byteArray = new byte[1024];
            int size = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while ((size = IOUtils.read(inputStream, byteArray)) != 0) {
                byteArrayOutputStream.write(byteArray, 0, size);
            }
            IOUtils.write(byteArrayOutputStream.toByteArray(), fileOutputStream);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    logger.error("e:{}", e.getMessage());
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("e:{}", e.getMessage());
                }
            }
        }
    }


    /**
     * 读取上传文件内容
     *
     * @param file
     * @return
     */
    public String readFile(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            byte[] byteArray = new byte[1024];
            int len;
            StringBuffer strBuf = new StringBuffer();
            while ((len = IOUtils.read(inputStream, byteArray)) != 0) {
                strBuf.append(new String(byteArray, 0, len, StandardCharsets.UTF_8));
            }
            return strBuf.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("e:{}", e.getMessage());
                }
            }
        }
    }

}

